<template>
  <div
    class="fixed top-[20%] left-1/2 translate-x-[-50%] bg-white w-[340px] h-[270px] text-sm dark:bg-zinc-800 rounded-sm border border-zinc-200 dark:border-zinc-900 shadow-md"
  >
    <!-- 头部 -->
    <div class="flex justify-between px-[10px] py-[15px]">
      <p class="flex-grow text-left">请完成安全验证</p>
      <img
        @click="handleRefresh"
        src="@/assets/style/svg/refresh.svg"
        class="w-[25px] cursor-pointer"
      />
      <span class="ml-[20px] text-xl cursor-pointer" @click="handleClose"
        >X</span
      >
    </div>

    <div id="captcha"></div>
  </div>
</template>

<script setup>
import { onMounted, defineEmits } from 'vue'
import '@/vendor/SliderCaptcha/longbow.slidercaptcha.min.js'
import '@/vendor/SliderCaptcha/slidercaptcha.min.css'
import { message } from '@/libs'
import { getCaptcha } from '@/server/api/sys'

const emits = defineEmits(['success', 'close'])

let captcha = null

/**
 * 刷新验证码
 */
const handleRefresh = () => {
  captcha.reset()
}

/**
 * 关闭窗口
 */
const handleClose = () => {
  emits('close')
}

/**
 * 重置验证码
 */
const resetCaptcha = () => {
  captcha.reset()
}

onMounted(() => {
  captcha = sliderCaptcha({
    // 渲染位置
    id: 'captcha',
    // 拼图吻合
    onSuccess: async function (arr) {
      const res = await getCaptcha({
        behavior: arr
      })
      if (res) {
        message('success', '验证成功ovo')
        emits('success')
      }
    },
    // 拼图失败
    onFail: function () {
      message('error', '验证失败x_x')
      resetCaptcha()
    },
    verify() {
      return true
    }
  })
})
</script>

<style lang="scss" scoped></style>
